import {IS_FOR_WX} from "../../AppConfig";

if (cc.sys.platform === cc.sys.WECHAT_GAME && IS_FOR_WX) {
  const API_CODE = require("apiCode");
  let apiCall = require("../../api/apiCall");
  let PlayerData = require("PlayerData");
  
  let _getUserInfo = function (callback) {
    console.log("getUserInfo");
    wx.getUserInfo({
      success: (res) => {
        console.log("wx.getUserInfo成功:", res);
        PlayerData.instance.applyUserInfo(res.userInfo);
        callback(Global.LoginState);
      },
      fail: function (res) {
        // iOS 和 Android 对于拒绝授权的回调 errMsg 没有统一，需要做一下兼容处理
        if (res.errMsg.indexOf('auth deny') > -1 || res.errMsg.indexOf('auth denied') > -1) {
          // 处理用户拒绝授权的情况
          callback(Global.LoginState);
        }
      }
    })
  };
  
  let login = function (callback) {
    //避免重复登录
    if (Global.LoginState.isLogin) {
      callback(Global.LoginState);
      return;
    }
    
    wx.login({
      success: function (res) {
        console.log("微信登录成功:", res);
        Global.LoginState.isLogin = true;
        Global.LoginState.loginCode = res.code;
        callback(Global.LoginState);
      },
      fail: function (res) {
        console.log("微信登录失败:", res);
        Global.LoginState.isLogin = false;
        callback(Global.LoginState);
      }
    });
  };
  
  let checkAuthorize = function (callback) {
    console.log("checkAuthorize");
    //避免重复授权
    if (Global.LoginState.isAuthorize) {
      callback(Global.LoginState);
      return;
    }
    
    wx.getSetting({
      success: (res) => {
        console.log("wx.getSetting成功:", res);
        let authSetting = res.authSetting;
        if (authSetting['scope.userInfo'] === true) {
          // 用户已授权，可以直接调用相关 API
          Global.LoginState.isAuthorize = true;
          _getUserInfo(callback);
          
        } else if (authSetting['scope.userInfo'] === false) {
          // 用户已拒绝授权，再调用相关 API 或者 wx.authorize 会失败，需要引导用户到设置页面打开授权开关
          Global.LoginState.isAuthorize = false;
          callback(Global.LoginState);
        } else {
          // 未询问过用户授权, 添加userInfoButton,弹窗询问授权
          let sysInfo = wx.getSystemInfoSync();
          let userInfoButton = null;
          
          userInfoButton = wx.createUserInfoButton({
            type: 'text',
            text: '',
            // image: 'images/start_button.png',
            withCredentials: true,
            style: {
              left: 0,
              top: 0,
              width: sysInfo.screenWidth,
              height: sysInfo.screenHeight,
              backgroundColor: '#00000000',
            }
          });
          userInfoButton.onTap((res) => {
            console.log(res);
            if (res.errMsg === "getUserInfo:ok") {
              console.log("授权用户信息");
              Global.LoginState.isAuthorize = true;
              _getUserInfo(callback);
              //清除微信授权按钮
              userInfoButton.destroy();
            } else {
              console.log("授权失败");
              // 处理用户拒绝授权的情况
              Global.Toast.show('请首先点击屏幕\n授权使用"用户信息"');
            }
          });
          Global.Toast.show('请首先点击屏幕\n授权使用"用户信息"');
        }
      },
      fail: (res) => {
        console.log("wx.getSetting失败:", res);
        Global.LoginState.isAuthorize = false;
        callback(Global.LoginState);
      }
    });
  };
  
  
  let loadGameData = function (callback) {
    apiCall.login((err, res) => {
      if (err) {
        Global.LoginState.gameServerLogin = false;
        callback(Global.LoginState);
      } else {
        if (res.code === API_CODE.SUCCEED) {
          Global.LoginState.gameServerLogin = true;
          PlayerData.instance.setNetData(res);
          
          callback(Global.LoginState);
        } else {
          Global.LoginState.gameServerLogin = false;
          callback(Global.LoginState);
        }
      }
    });
  };

  let loadUserInfo = function (callback) {
    _getUserInfo(callback);
  };


  module.exports = {
    login,
    checkAuthorize,
    loadGameData,
    loadUserInfo
  }
}